﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

public partial class Controls_AdminMenu : System.Web.UI.UserControl
{
    public string StartNodeUrl
    {
        get;
        set;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        DataBind();
    }

    public override void DataBind()
    {
        if (SiteMap.Provider.RootNode != null)
        {
            StringBuilder menuHtml = new StringBuilder("<ul class=\"sf-menu\">");
            SiteMapNode startNode = FindStartNode(SiteMap.Provider.RootNode);
            menuHtml.Append(CreateMenu(startNode.ChildNodes));
            menuHtml.Append("</ul>");
            Literal literal = new Literal();
            literal.Text = menuHtml.ToString();
            Controls.Add(literal);
        }
    }

    private SiteMapNode FindStartNode(SiteMapNode node)
    {
        if (node.Url == ResolveUrl(StartNodeUrl))
            return node;
        else if (!node.HasChildNodes)
            return null;
        else
        {
            foreach (SiteMapNode n in node.ChildNodes)
            {
                SiteMapNode rn = FindStartNode(n);
                if (rn != null)
                    return rn;
            }
            return null; 
        }
    }

    private string CreateMenu(SiteMapNodeCollection siteMapNodeCollection)
    {
        StringBuilder segment = new StringBuilder();
        foreach (SiteMapNode node in siteMapNodeCollection)
        {
            // Collecting roles for security verification
            bool userInRole = false;
            foreach (object role in node.Roles)
            {
                string roleName = role as string;
                if (roleName == "*")
                    userInRole = true;
                else if (Roles.Provider.IsUserInRole(Page.User.Identity.Name, roleName))
                    userInRole = true;
            }

            if (userInRole && Convert.ToBoolean(node["visible"]))
            {
                // setting up the link
                if (SiteMap.CurrentNode.IsDescendantOf(node) || SiteMap.CurrentNode == node)
                    segment.Append("<li><a class=\"current\" href=\"").Append(node.Url).Append("\">").Append(node.Title).Append("</a>");
                else
                    segment.Append("<li><a href=\"").Append(node.Url).Append("\">").Append(node.Title).Append("</a>");

                if (node.HasChildNodes)
                    segment.Append("<ul>").Append(CreateMenu(node.ChildNodes)).Append("</ul>");

                segment.Append("</li>");
            }
        }
        return segment.ToString();
    }
}
